/*
 * Copyright (c) 2013, marco.tamburelli@gmail.com
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met: 
 * 
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer. 
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution. 
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package org.bmi.gwt.mi.server.impl;

import java.lang.reflect.Constructor;

import org.bmi.gwt.mi.server.util.ServerUtil;
import org.bmi.gwt.mi.shared.MiObject;
import org.bmi.gwt.mi.shared.MiProxy;
import org.bmi.gwt.mi.shared.annotations.TargetMiObjectClass;
import org.bmi.gwt.mi.shared.communication.var.ReturnVar;
import org.bmi.gwt.mi.shared.exceptions.InvalidArgumentException;
import org.bmi.gwt.mi.shared.exceptions.NotAvailableConstructorException;
import org.bmi.gwt.mi.shared.util.ProxyBase;

/**
 * Class designed as base for a server side proxy. It's for internal use only.
 */
class ProxyBaseServer extends ProxyBase
{
	/**
	 * Constructor with no arguments; it should be used to create a proxy to a
	 * registered object (not defined by any constructor).
	 * 
	 * @param targetClass The class of the target object.
	 */
	protected ProxyBaseServer(Class<? extends MiObject> targetClass)
	{
		super.targetMiObjectClass = targetClass;
	}

	/**
	 * Constructor used when arguments for the constructor of target class are
	 * required. Should be used to create a proxy which register an object by
	 * its constructor.
	 * 
	 * @param targetClass
	 * @param args
	 * @throws NotAvailableConstructorException
	 */
	protected ProxyBaseServer(Class<? extends MiObject> targetClass, Object[] args)
			throws NotAvailableConstructorException
	{
		super.targetMiObjectClass = targetClass;
		super.constrPublisher = new ProxyConstructor()
		{
			@Override
			public void doConstructor(Object[] args) throws InvalidArgumentException
			{
				ProxyBaseServer.super.publisher.publishConstructor(ProxyBaseServer.super.objectId,
						ProxyBaseServer.super.targetMiObjectClass, ProxyBaseServer.super.constrSignature,
						ParamConverter.convertObjects(args));
			}
		};

		Constructor<?>[] constructors = targetClass.getConstructors();

		for (Constructor<?> constructor : constructors)
			if (checkConstructor(constructor.getParameterTypes(), args)) return;

		throw new NotAvailableConstructorException();
	}

	private boolean checkConstructor(Class<?>[] params, Object[] args)
	{
		if (params.length != args.length) return false;

		StringBuilder ctorSignature = new StringBuilder();

		for (int i = 0; i < params.length; i++)
		{
			Object arg = args[i];
			/*
			 * In case the argument is a proxy it should implement an interface
			 * having an annotation defining the target object, and from that
			 * element it's possible to obtain the type of the argument of the
			 * target constructor
			 */
			TargetMiObjectClass anno = null;

			if (arg instanceof MiProxy) for (Class<?> in : arg.getClass().getInterfaces())
				if (MiProxy.class.isAssignableFrom(in))
				{
					anno = in.getAnnotation(TargetMiObjectClass.class);
					break;
				}

			String jsni = ServerUtil.getJNISignature(params[i]);

			if (params[i].isInstance(arg) || (arg instanceof ReturnVar && jsni.equals(((ReturnVar<?>) arg).getJsni()))
					|| (anno != null && params[i].isAssignableFrom(anno.miObjectClass())))
				ctorSignature.append(jsni);
			else
				return false;
		}

		super.constrSignature = ctorSignature.toString();

		return true;
	}
}
